﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MoAds.CustomAdServiceSite.Models;

namespace MoAds.CustomAdServiceSite.Controllers
{
    /// <summary>
    /// The structure of the response
    /// </summary>
    public class FetchResponse
    {
        public string ImageUrl { get; set; }
        public string AdText { get; set; }
        public string ClickUrl { get; set; }
    }

    /// <summary>
    /// Impression information for tracking.
    /// </summary>
    public class Impression
    {
        public string Token { get; set; }
        public long AdId { get; set; }
    }

    /// <summary>
    /// An in memory repository for impressions.
    /// </summary>
    internal static class ImpressionRepository
    {
        public static List<Impression> Impressions = new List<Impression>();
    }

    /// <summary>
    /// The controller responsible for serving ad information.
    /// </summary>
    public class AdController : Controller
    {
        public const string clickBaseUrl = "http://localhost:53339/Ad/Click/";

        public ActionResult Fetch(string pubId, string clientId = "")
        {
            // TODO: You'd probably want to keep track of fetches by PubId for analytics, but this is just a demo.

            var ad = AdRepository.GetRandomAd();
            Impression impression;
            var clickUrl = GenerateClickUrl(ad, out impression);

            ImpressionRepository.Impressions.Add(impression);

            return new JsonResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new FetchResponse()
                {
                    ClickUrl = clickUrl,
                    AdText = ad.AdText,
                    ImageUrl = ad.ImageUrl
                }
            };
        }

        public ActionResult Click(string id)
        {
            // TODO: Track the click for analytics and what-not.

            var impression = ImpressionRepository.Impressions.FirstOrDefault(x => x.Token == id);
            if (impression == null)
                return View(); // TODO: return not found result.

            var ad = AdRepository.GetAdById(impression.AdId);
            return new RedirectResult(ad.AdUrl);
        }

        private string GenerateClickUrl(AdInfo ad, out Impression impression)
        {
            impression = new Impression()
            {
                Token = Guid.NewGuid().ToString().Substring(0, 10).Replace("-", string.Empty),
                AdId = ad.Id
            };

            return string.Concat(clickBaseUrl, impression.Token);
        }
    }
}
